package com.hsxc.cdz.controller.appController;

import com.hsxc.cdz.base.bean.Pile;
import com.hsxc.cdz.mgmt.pile.PileManager;
import com.hsxc.cdz.mgmt.station.StationManager;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * app充电桩
 *
 * @author admin
 */
@Controller("appPile")
@RequestMapping("/app")
public class PileController {

    /************************************************************/
    // 自动注入属性
    @Autowired
    private StationManager stationManager;
    @Autowired
    private PileManager pileManager;

    Logger logger = LoggerFactory.getLogger(PileController.class);

    @RequestMapping(value = "/getPile", method = RequestMethod.GET)
    @ResponseBody
    public Object getPile(@RequestParam("stationNo") String stationNo) {
        JSONObject result = new JSONObject();
        List<Pile> piles = pileManager.getPilesByStationNo(stationNo);
        result.put("success", true);
        if (piles == null || piles.size() == 0) {
            result.put("errvode", 1);
            result.put("message", "无数据");
        }
        result.put("errcode", 0);
        result.put("message", "查询成功");
        return result;
    }

    @RequestMapping(value = "/searchPile", method = RequestMethod.POST)
    @ResponseBody
    public Object getLatLong(@RequestBody String param) {
        logger.info("SEARCH PILE START...");
        JSONObject params = JSONObject.fromObject(param);
        JSONObject result = new JSONObject();
        List<Pile> piles = null;

        result.put("success", true);
        int pileType = 1;
        String speed = null;
        if (params.has("property"))
            pileType = params.getInt("property");
        if (params.has("speed"))
            speed = params.getString("speed");
        piles = pileManager.searchPile(pileType, speed);
        if (piles == null || piles.size() == 0) {
            result.put("errcode", 1);
            result.put("message", "没有桩");
        }
        result.put("errcode", 0);
        result.put("message", piles);
        return result;
    }

    @RequestMapping(value = "/station", method = RequestMethod.GET)
    @ResponseBody
    public Object getStation(@RequestParam("latitude") double latitude, @RequestParam("longitude") double longitude,
                             @RequestParam("raidus") int raidus, HttpServletRequest request) {
        logger.info("进入充电站获取界面");
        JSONObject data = new JSONObject();
        data.put("success", true);
        Subject appUser = SecurityUtils.getSubject();
        logger.info("APP USER'S PRINCIPAL" + appUser.getPrincipal());
        logger.info("APP USER'S REQUEST HEAD" + request.getHeaderNames());
        logger.info("APP USER'S REQUEST HEAD" + request.getHeaderNames());
        logger.info("APP USER'S REQUEST HEAD SID IS " + request.getHeader("sid"));
        logger.info("PARAM LATITUDE IS " + latitude + "LONGITUDE IS " + longitude);
        double[] range = this.getAround(latitude, longitude, raidus);
        for (int i = 0; i < range.length; i++) {
            logger.info("---经纬度范围----" + range[i]);
        }
        List<Map<String, Object>> result = stationManager.getByLatlong(range);
        if (result != null) {
            for (int i = 0; i < result.size(); i++) {
                Map<String, Object> resultMap = result.get(i);
                long count = (long) resultMap.get("count");
                double lon = (double) resultMap.get("longitude") / count;
                double lat = (double) resultMap.get("latitude") / count;
                double distance = this.distance(longitude, latitude, lon, lat);
                resultMap.put("distance", distance);
                resultMap.remove("longitude");
                resultMap.remove("latitude");
                resultMap.put("longitude", lon);
                resultMap.put("latitude", lat);
            }
        }
        data.put("data", result);
        logger.info(data.toString());
        return data;

    }

    /**
     * 根据半径和经纬度算经纬度范围
     *
     * @param lat    纬度
     * @param lon    经度
     * @param raidus 半径
     * @return 经纬度范围的数组
     */
    public double[] getAround(double lat, double lon, int raidus) {

        Double latitude = lat;
        Double longitude = lon;

        Double degree = (24901 * 1609) / 360.0;
        double raidusMile = raidus;

        Double dpmLat = 1 / degree;
        Double radiusLat = dpmLat * raidusMile;
        Double minLat = latitude - radiusLat;
        Double maxLat = latitude + radiusLat;

        Double mpdLng = degree * Math.cos(latitude * (Math.PI / 180));
        Double dpmLng = 1 / mpdLng;
        Double radiusLng = dpmLng * raidusMile;
        Double minLng = longitude - radiusLng;
        Double maxLng = longitude + radiusLng;
        return new double[]{minLat, maxLat, minLng, maxLng};
    }

    /**
     * 计算地球上任意两点(经纬度)距离
     *
     * @param long1 第一点经度
     * @param lat1  第一点纬度
     * @param long2 第二点经度
     * @param lat2  第二点纬度
     * @return 返回距离 单位：米
     */
    public double distance(double long1, double lat1, double long2, double lat2) {
        double a, b, R;
        R = 6378137; // 地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
        return d;
    }
}
